package xuegao.study.mall.job.controller;

import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xuegao.study.mall.common.api.CommonResult;
import xuegao.study.mall.common.model.job.SysJob;
import xuegao.study.mall.job.service.ISysJobService;
import xuegao.study.mall.job.util.Constant;
import xuegao.study.mall.job.util.SchedulerUtil;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/job2")
public class JobControllerV2 {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysJobService sysJobService;

    @ApiOperation("新增任务")
    @PostMapping(value = "/addJob")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addJob(@RequestBody SysJob sysJob) {
        logger.info("add a job info:{}", sysJob);
        sysJob.setJobStatus(Constant.JOB_STATE.YES);
        try {
            int count = sysJobService.insertSelective(sysJob);
            SchedulerUtil.addJob(
                    sysJob.getJobClassPath(),
                    sysJob.getJobName(),
                    sysJob.getJobGroup(),
                    sysJob.getJobCron(),
                    sysJob.getJobDataMap());
            return CommonResult.success(count);
        } catch (Exception e) {
            logger.info("add a job error", e);
            throw new RuntimeException(e);
        }
    }

    @ApiOperation("删除任务")
    @PostMapping(value = "/deleteJob")
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult deleteJob(@RequestParam(value = "id") Long id) {
        try {
            SysJob sysJob = sysJobService.selectByPrimaryKey(id);
            int num = sysJobService.deleteByPrimaryKey(id);
            SchedulerUtil.jobdelete(sysJob.getJobName(), sysJob.getJobGroup());
            return CommonResult.success(num);
        } catch (Exception e) {
            logger.info("delete a job error", e);
            throw new RuntimeException(e);
        }
    }

    @ApiOperation("修改定时表达式")
    @PostMapping("/reScheduleJob/{id}")
    public CommonResult updateByBean(@PathVariable Long id, @RequestParam String jobCron, @RequestParam String jobDescribe) {
        try {
            SysJob result = sysJobService.selectByPrimaryKey(id);
            SysJob bean = new SysJob();
            bean.setId(id);
            bean.setJobCron(jobCron);
            bean.setJobDescribe(jobDescribe);
            int num = sysJobService.updateByPrimaryKeySelective(bean);
            // 只有任务状态为启用，才开始运行
            // 如果先启动再手工插入数据，此处会报空指针异常
            if( result.getJobStatus() ==Constant.JOB_STATE.YES ){
                SchedulerUtil.jobReschedule(result.getJobName(), result.getJobGroup(),jobCron);
            }
            return CommonResult.success(num);
        } catch (Exception e) {
            logger.info("change job cron error", e);
            throw new RuntimeException();
        }
    }

    @ApiOperation("变更任务执行状态")
    @PostMapping(value = "/changeState/{id}")
    public CommonResult changeState(@PathVariable Long id) {
        try {
            SysJob sysJob = sysJobService.selectByPrimaryKey(id);
            SysJob updateBean = new SysJob();
            updateBean.setId(id);
            //如果是现在是启用，则停用
            if(Constant.JOB_STATE.YES == sysJob.getJobStatus()){
                updateBean.setJobStatus(Constant.JOB_STATE.NO);
                Boolean b = SchedulerUtil.isResume(sysJob.getJobName(), sysJob.getJobGroup());
                if (b) {
                    SchedulerUtil.jobdelete(sysJob.getJobName(), sysJob.getJobGroup());
                }
            }
            //如果现在是停用，则启用
            if(Constant.JOB_STATE.NO == sysJob.getJobStatus()){
                updateBean.setJobStatus(Constant.JOB_STATE.YES);
                Boolean b=SchedulerUtil.isResume(sysJob.getJobName(), sysJob.getJobGroup());
                //存在则激活，不存在则添加
                if (b) {
                    SchedulerUtil.jobresume(sysJob.getJobName(), sysJob.getJobGroup());
                }else {
                    SchedulerUtil.addJob(sysJob.getJobClassPath(),sysJob.getJobName(), sysJob.getJobGroup(), sysJob.getJobCron(),sysJob.getJobDataMap());
                }
            }
            int count = sysJobService.updateByPrimaryKeySelective(updateBean);
            return CommonResult.success(count);
        } catch (Exception e) {
            logger.info("change job state error", e);
            throw new RuntimeException();
        }
    }

    @ApiOperation("任务列表")
    @GetMapping(value = "/queryList")
    public CommonResult queryLis() {
        HashMap<String, String> map = new HashMap<String, String>();
        List<SysJob> jobList = sysJobService.querySysJobList(map);
        for (SysJob job : jobList) {
            String statusStr = job.getJobStatus() == 0 ? "禁用" : "启动";
            job.setJobStatusStr(statusStr);
        }
        return CommonResult.success(jobList);
    }
}
